import request from '@/request/request'
import axios from 'axios'

// 获取所有周刊
export function getAllWeekly() {
  return request({
    url: '/api/admin/weekly/getAllWeekly',
    method: 'get'
  })
}

// 分页获取周刊
export function getWeeklyPage(pageNum = 1, pageSize = 10, title = '', minLikes = null, maxLikes = null) {
  const params = { pageNum, pageSize }
  
  // 添加可选查询参数
  if (title) {
    params.title = title
  }
  
  if (minLikes !== null) {
    params.minLikes = minLikes
  }
  
  if (maxLikes !== null) {
    params.maxLikes = maxLikes
  }
  
  return request({
    url: '/api/admin/weekly/getWeeklyPage',
    method: 'get',
    params
  })
}

// 根据ID获取周刊
export function getWeeklyById(id) {
  console.log('Getting weekly by ID:', id)
  return request({
    url: '/api/admin/weekly/getWeeklyById',
    method: 'get',
    params: { id }
  })
}

// 上传周刊PDF文件
export function uploadWeeklyPdf(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  // 使用axios直接发送请求，避开request拦截器对Content-Type的修改
  return axios({
    url: 'http://localhost:8080/api/admin/weekly/uploadPdf',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(response => {
    return response.data;
  }).catch(error => {
    console.error('上传PDF失败:', error);
    return Promise.reject(error);
  });
}

// 添加周刊
export function createWeekly(data) {
  console.log('Creating weekly with data:', data)
  // 确保数据格式符合后端要求
  const weeklyData = {
    ...data,
    // 转换字段名称以匹配后端 (如果需要)
    weeklyTitle: data.weekly_title || data.weeklyTitle,
    fileUrl: data.file_url || data.fileUrl,
    weekltDescription: data.weeklt_description || data.weekltDescription,
    likeNumbers: data.like_numbers || data.likeNumbers || 0,
    deleteFlag: data.delete_flag || data.deleteFlag || 0
  }
  
  return request({
    url: '/api/admin/weekly/createWeekly',
    method: 'post',
    data: weeklyData
  })
}

// 修改周刊
export function updateWeekly(data) {
  console.log('Updating weekly with data:', data)
  // 确保数据格式符合后端要求
  const weeklyData = {
    ...data,
    // 转换字段名称以匹配后端 (如果需要)
    weeklyTitle: data.weekly_title || data.weeklyTitle,
    fileUrl: data.file_url || data.fileUrl,
    weekltDescription: data.weeklt_description || data.weekltDescription,
    likeNumbers: data.like_numbers || data.likeNumbers || 0,
    deleteFlag: data.delete_flag || data.deleteFlag || 0
  }
  
  return request({
    url: '/api/admin/weekly/updateWeekly',
    method: 'post',
    data: weeklyData
  })
}

// 删除周刊
export function deleteWeekly(id) {
  console.log('Deleting weekly with ID:', id)
  return request({
    url: '/api/admin/weekly/deleteWeekly',
    method: 'delete',
    params: { id }
  })
}